var jisuan = [
    {id: "0", code: " ", name: " "},
    {id: "1", code: "SUM", name: "SUM"},
    {id: "2", code: "COUNT", name: "COUNT"}
];

var sqlEditWindow = {
    window: null,
    show: function () {
        this.window = createSqlEditWindow();
        this.window.show();
        // 回显数据
        analysisSql();
    },
    close: function () {
        this.window.close();
    }
};

var field_treeGridStore;
var global_params = [];//全局的请求参数
var flag1 = true; //点击数据字段是否发送请求的标志，
var arrayTableName = [];//从表单获取的表名
var arrayField = []; //从表单获取的字段
var arrayGroup = []; //从表单获取的分组的字段
var arrayOrder = []; //从表单获取的排序的字段
var arrayJuhe = [];

/**
 *  创建sql编辑器窗口
 * @returns {Ext.window.Window}
 */
function createSqlEditWindow() {
    return Ext.create('Ext.window.Window', {
        title: 'SQL编辑器', // 窗口标题
        width: document.body.clientWidth * 0.7, // 窗口宽度
        height: document.body.clientHeight * 0.7, // 窗口高度
        layout: 'fit',
        border: false,
        maximizable: true,
        buttonAlign: 'right', // 按钮显示的位置
        modal: true, // 模式窗口，弹出窗口后屏蔽掉其他组件
        closeAction: 'destroy',
        buttons: [
            {
                xtype: 'button',
                text: '确定',
                handler: function (self) {
                    //调用sql拼接函数
                    jointSQL();
                    //重置请求参数
                    global_params = [];

                    //获取到之前编辑的数据
                    self.up('window').close();
                }
            }, {
                xtype: 'button',
                text: '关闭',
                handler: function (self) {
                    global_params = [];
                    self.up('window').close();
                }
            }
        ],
        items: [
            create_tab_panel() //创建多页标签的一个tab_panel(相当于一个div)
        ]
    });
}

/**
 * 解析sql回显到sql编辑器
 *
 */
function analysisSql() {
    //获取编辑框中的sql语句
    var editSql = Ext.ComponentQuery.query('textareafield[name="EDIT_SQL"]')[0].getValue();
    editSql = editSql.toUpperCase().trim();
    if (editSql !== "") { //标识编辑则开始获取数据
        //判断获取的内容是否包含关联关系
        var tableName;
        if (editSql.includes("JOIN")) {
            tableName = editSql.substring(editSql.indexOf('FROM') + 'FROM'.length, editSql.indexOf('JOIN'))
                .split("\n")[0].replace(/(^\s*)/g, "");
        } else if (editSql.includes("WHERE")) {
            tableName = editSql.substring(editSql.indexOf('FROM') + 'FROM'.length, editSql.indexOf('WHERE'))
                .split("\n")[0].replace(/(^\s*)/g, "");
        } else {
            tableName = editSql.substring(editSql.indexOf('FROM') + 'FROM'.length)
                .split("\n")[0].replace(/(^\s*)/g, "");
        }
        //去掉字符串两端空格
        tableName = tableName.trim().split(" ")[0];

        //截取关联的表名
        if (editSql.includes("JOIN")) {
            var tableName2 = editSql.substring(editSql.indexOf('JOIN') + 'JOIN'.length, editSql.indexOf('ON '))
                .split("\n")[0].replace(/(^\s*)/g, "");
            tableName2 = tableName2.split(" ")[0]; //通过空格分割，然后拿取表名
        }

        arrayTableName.push(tableName);
        //表示选中的是两个表
        if (tableName2 != undefined) {
            arrayTableName.push(tableName2);
        }
        var tableData = [];
        if (arrayTableName.length != 1) {
            for (var i = 0; i < arrayTableName.length; i++) {
                tableData.push(
                    {
                        id: arrayTableName[i],
                        code: arrayTableName[i],
                        text: arrayTableName[i]
                    }
                );
            }
        } else {
            tableData.push(
                {
                    id: arrayTableName[0],
                    code: arrayTableName[0],
                    text: arrayTableName[0]
                }
            );
        }

        // 表关联
        //获取from 到 where 之间的sql--关联页签需要的数据
        if (editSql.includes("WHERE")) {
            var from = editSql.substring(editSql.indexOf('FROM'), editSql.indexOf('WHERE'));
            from = from.substring(0, from.length - 1);
        } else if (editSql.includes("GROUP")) {
            from = editSql.substring(editSql.indexOf('FROM'), editSql.indexOf('GROUP'));
            from = from.substring(0, from.length - 1);
        } else if (editSql.includes("ORDER")) {
            from = editSql.substring(editSql.indexOf('FROM'), editSql.indexOf('ORDER'));
            from = from.substring(0, from.length - 1);
        } else {
            from = editSql.substring(editSql.indexOf('FROM'));
        }
        // 解析表别名
        var keywords = ['FROM', 'LEFT', 'RIGHT', 'INNER', 'ON', ','];
        tableAlias = [];
        var joinSplits = from.split(/\s+/);
        $.each(joinSplits, function (index, word) {
            $(tableData).each(function () {
                if (word === this.code) {
                    if (!!joinSplits[index + 1] && keywords.indexOf(joinSplits[index + 1]) === -1) {
                        tableAlias.push({tableName: this.code, tableAlias: joinSplits[index + 1]});
                    }
                    return false;
                }
            });
        });

        //判断是否选择了单独的字段
        var field;
        if (editSql.includes("SELECT")) {
            if (editSql.includes("FROM")) {
                field = editSql.substring(editSql.indexOf('SELECT') + 'SELECT'.length, editSql.indexOf('FROM'))
                if (field === "*") {
                } else {
                    // 如果有别名，替换别名为表本身的名字
                    if (!!tableAlias) {
                        $(tableAlias).each(function () {
                            field = field.replaceAll(this.tableAlias + "\\.", this.tableName + ".");
                        });
                    }

                    field = field.replaceAll(/\t|\n|\v|\r|\f|\s/g, "");
                    arrayField = field.split(",");
                    arrayField = $.grep(arrayField, function (x) {
                        return x.trim().length > 0;
                    });
                }
            }
        }
        //统计聚合函数出现
        if (field.includes("COUNT")) {
            //var result = kuohao(field);
            //统计count出现的次数
            var count = getStrCount(field, "COUNT");
            var index = 0;
            for (var i = 0; i < count; i++) {
                //获取聚合函数中的字段 用来根据字段的id进行回填
                var juheId = field.substring(field.indexOf("COUNT(", index) + "COUNT(".length, field.indexOf(")", field.indexOf("COUNT(", index)));
                index = field.indexOf(")", field.indexOf("COUNT(", index));
                arrayJuhe.push({"id": juheId, "doit": "COUNT"});
            }
        }
        if (field.includes("SUM")) {
            //var result = kuohao(field);
            //统计count出现的次数
            var count = getStrCount(field, "SUM");
            var index = 0;
            for (var i = 0; i < count; i++) {
                var juheId = field.substring(field.indexOf("SUM(", index) + "SUM(".length, field.indexOf(")", field.indexOf("SUM(", index)));
                index = field.indexOf(")", field.indexOf("SUM(", index));
                arrayJuhe.push({"id": juheId, "doit": "SUM"});
            }
        }
        //获取where 到group by之间的sql
        var where;
        if (editSql.includes("WHERE")) {
            if (editSql.includes("GROUP")) {
                where = editSql.substring(editSql.indexOf('WHERE') + 'WHERE'.length, editSql.indexOf('GROUP'));
            } else if (editSql.includes("ORDER")) {
                where = editSql.substring(editSql.indexOf('WHERE') + 'WHERE'.length, editSql.indexOf('ORDER'));
            } else {
                where = editSql.substring(editSql.indexOf('WHERE') + 'WHERE'.length);
            }
            where = where.replace(/^\s*/g, "");
            where = where.substring(0, where.length - 1);
        } else {
            where = "";
        }
        //判断是否包含GROUP
        var groupby;
        if (editSql.includes("GROUP")) {
            if (editSql.includes("ORDER")) {
                groupby = editSql.substring(editSql.indexOf('GROUP') + 'GROUP BY'.length, editSql.indexOf('ORDER'))
            } else {
                groupby = editSql.substring(editSql.indexOf('GROUP') + 'GROUP BY'.length).replace(/[ ]/g, "");
            }
            // 如果有别名，替换别名为表本身的名字
            if (!!tableAlias) {
                $(tableAlias).each(function () {
                    groupby = groupby.replaceAll(this.tableAlias + "\\.", this.tableName + ".");
                });
            }

            //先判断是不是多个字段分组
            var groupData = [];
            if (groupby.includes(",")) {
                //将分组的字段分割
                var strs = groupby.split(",");
                //遍历分组字段，构建表名 列名 以及id
                for (var i = 0; i < strs.length; i++) {
                    var id = strs[i].split(".")[0].replace(/[\r\n]/g, "") + "." + strs[i].split(".")[1].replace(/[\r\n]/g, "");
                    arrayGroup.push(id.trim());//回显数据时去掉空格
                    groupData.push(
                        {
                            "parentId": strs[i].split(".")[0].replace(/[\r\n]/g, "").trim(),
                            "code": strs[i].split(".")[1].replace(/[\r\n]/g, "").trim(),
                            "id": strs[i].split(".")[0].replace(/[\r\n]/g, "").trim() + "." + strs[i].split(".")[1].replace(/[\r\n]/g, "").trim()
                        }
                    );
                }
            } else {
                arrayGroup.push(groupby.trim());
                groupData.push(
                    {
                        "parentId": groupby.split(".")[0].replace(/[\r\n]/g, "").trim(),
                        "code": groupby.split(".")[1].replace(/[\r\n]/g, "").trim(),
                        "id": groupby.split(".")[0].replace(/[\r\n]/g, "").trim() + "." + groupby.split(".")[1].replace(/[\r\n]/g, "").trim()
                    }
                );
            }

        } else {
            groupby = "";
        }
        //判断是否包含Order by
        var orderby;
        if (editSql.includes("ORDER")) {
            orderby = editSql.substring(editSql.indexOf('ORDER') + 'ORDER BY'.length).replace(/(^\s*)/g, "");
            // 如果有别名，替换别名为表本身的名字
            if (!!tableAlias) {
                $(tableAlias).each(function () {
                    orderby = orderby.replaceAll(this.tableAlias + "\\.", this.tableName + ".");
                });
            }

            var orderData = [];
            if (orderby.includes(",")) {
                var strs = orderby.split(",");
                for (var i = 0; i < strs.length; i++) {
                    var parentId = strs[i].split(".")[0].replace(/[\r\n]/g, "");
                    var code = strs[i].split(".")[1].split(" ")[0].replace(/[\r\n]/g, "").trim();
                    var sort = strs[i].split(".")[1].split(" ")[1].replace(/[\r\n]/g, "").trim();
                    var id = strs[i].split(".")[0].replace(/[\r\n]/g, "").trim() + "." + strs[i].split(".")[1].split(" ")[0].replace(/[\r\n]/g, "").trim();
                    arrayOrder.push(id.trim());
                    orderData.push(
                        {
                            "parentId": parentId,
                            "code": code,
                            "SORT": sort,
                            "id": id
                        }
                    );
                }
            } else {
                arrayOrder.push(orderby.split(" ")[0].trim());
                orderData.push(
                    {
                        "parentId": orderby.split(".")[0].replace(/[\r\n]/g, ""),
                        "code": orderby.split(".")[1].split(" ")[0].replace(/[\r\n]/g, ""),
                        "SORT": orderby.split(".")[1].split(" ")[1].replace(/[\r\n]/g, ""),
                        "id": orderby.split(".")[0].replace(/[\r\n]/g, "") + "." + orderby.split(".")[1].split(" ")[0].replace(/[\r\n]/g, "")
                    }
                );
            }
        } else {
            orderby = "";
        }
        //关联页签回显数据
        Ext.ComponentQuery.query('textareafield[name="EDIT_SQL"]')[1].setValue(from);
        //条件页签回显数据
        Ext.ComponentQuery.query('textareafield[name="EDIT_SQL1"]')[0].setValue(where);
        //给分组回显数据
        if (DSYGrid.getGrid("groupGrid").getStore().data.items.length === 0) {
            DSYGrid.getGrid("groupGrid").insertData(0, groupData);
        }
        //给排序设置回显数据
        if (DSYGrid.getGrid("sortOrderGrid").getStore().data.items.length === 0) {
            DSYGrid.getGrid("sortOrderGrid").insertData(0, orderData);
        }
        //给数据表页签右侧表格设置回显数据
        DSYGrid.getGrid("tableOrderGrid").insertData(0, tableData);
    }

}

/**
 * 创建一个页签画板
 * @liqiang创建整个文件
 */
function create_tab_panel() {
    var tab_panel = Ext.create('Ext.tab.Panel', {
        //添加配置项
        tabPosition: 'top',//标签名显示的位置
        border: true,  //有边框
        fitToFrame: true,
        scrollable: true, //滚动条
        itemId: 'tabPanel',
        items: [
            {
                xtype: 'panel',
                title: '数据表',
                width: 200,
                height: '100%',
                border: true,
                layout: 'border',
                lines: false,
                items: [
                    initTableTreeLeft(), //初始化数据表左侧的树
                    initTableGridRight() //初始化数据表右侧的表格
                ]
            },
            {
                xtype: 'panel',
                title: '数据字段',
                width: 200,
                height: '100%',
                border: true,
                layout: 'border',
                lines: false,
                scrollable: true, //滚动条
                items: [
                    initColumnTreeGridPanel() //初始化数据列表格树
                ],
                listeners: {
                    activate: function () {
                        if (flag1) {
                            //获取选中的表名
                            var json_param = getDataFromTable();
                            var params = [];
                            for (var i = 0; i < json_param.length; i++) {
                                params.push(json_param[i].code);
                            }
                            if (global_params.length == params.length && global_params.sort().toString() == params.sort().toString()) {
                                flag1 = true;
                                return;
                            }
                            global_params = params;
                            field_treeGridStore.getProxy().extraParams = {
                                tableNames: params
                            };  //设置请求参数
                            field_treeGridStore.reload();
                        } else {
                            var json_param = getDataFromTable();
                            var params = [];
                            for (var i = 0; i < json_param.length; i++) {
                                params.push(json_param[i].code);
                            }
                            if (global_params.length == params.length && global_params.sort().toString() == params.sort().toString()) {
                                flag1 = false;
                                return;
                            }
                            global_params = params;
                            field_treeGridStore.getProxy().extraParams = {
                                tableNames: params
                            };  //设置请求参数
                            field_treeGridStore.reload();
                        }
                    }
                }

            },
            {
                xtype: 'panel',
                title: '关联',
                width: 200,
                height: '100%',
                border: true,
                layout: 'border',
                lines: false,
                buttonAlign: 'right',
                items: [
                    //创建一个panel
                    createGridForJoin()
                ],
                listeners: {
                    activate: function () {
                        var Table = "";
                        //获取选中的表名
                        //清空上次选择的表
                        var allSelecteTableName = getDataFromTable();
                        for (var i = 0; i < allSelecteTableName.length; i++) {
                            if (i == allSelecteTableName.length - 1) {
                                Table = Table + allSelecteTableName[i].code;
                                break;
                            }
                            Table = Table + allSelecteTableName[i].code;
                            Table = Table + "  ||  "
                        }
                        Ext.ComponentQuery.query('textareafield[name="TableSelected"]')[0].setValue(Table);
                    }
                }
            },
            {
                xtype: 'panel',
                title: '条件',
                width: 200,
                height: '100%',
                border: true,
                layout: 'border',
                lines: false,
                buttonAlign: 'right',
                items: [
                    //创建一个panel
                    createGridForWhere()
                ],
                listeners: {
                    activate: function () {
                        var Table = "";
                        //获取选中的表名
                        //清空上次选择的表
                        var allSelecteTableName = getDataFromTable();
                        for (var i = 0; i < allSelecteTableName.length; i++) {
                            if (i == allSelecteTableName.length - 1) {
                                Table = Table + allSelecteTableName[i].code;
                                break;
                            }
                            Table = Table + allSelecteTableName[i].code;
                            Table = Table + "  ||  "
                        }
                        Ext.ComponentQuery.query('textareafield[name="TableSelected1"]')[0].setValue(Table);
                    }
                }
            },
            {
                xtype: 'panel',
                title: '分组',
                width: 200,
                height: '100%',
                border: true,
                layout: 'border',
                lines: false,
                items: [
                    initGroupByTreeLeft(),//初始化数据列左侧的树
                    initGroupByGridRigth() //初始化数据列右侧的表格
                ],
                listeners: {
                    activate: function () {
                        ///获取下拉框对象
                        var comboboxObj = Ext.ComponentQuery.query('combobox[name="tableCombobox2"]')[0];
                        //获取选中的表名
                        var json_param1 = getDataFromTable();
                        //给下拉框对象设置值
                        comboboxObj.setStore(DebtEleStore(json_param1));

                        comboboxObj.getStore().addListener('load', function (store) {
                            var combobox = Ext.ComponentQuery.query('combobox[name="tableCombobox2"]')[0];
                            var length = store.getData().length;
                            if (length > 0) {
                                var defaultValue = store.getData().items[0].id;
                                if (!!defaultValue) {
                                    combobox.setValue(defaultValue);
                                }
                            }
                        });
                        comboboxObj.getStore().load();
                    }
                }
            },
            {
                xtype: 'panel',
                title: '排序',
                width: 200,
                height: '100%',
                border: true,
                layout: 'border',
                lines: false,
                items: [
                    initOrderByTreeLeft(),//初始化数据列左侧的树
                    initOrderByGridRigth() //初始化数据列右侧的表格
                ],
                listeners: {
                    activate: function () {
                        //获取选中的表名
                        var json_param1 = getDataFromTable();
                        ///获取下拉框对象
                        var comboboxObj = Ext.ComponentQuery.query('combobox[name="tableCombobox1"]')[0];
                        //给下拉框对象设置值
                        comboboxObj.setStore(DebtEleStore(json_param1));

                        comboboxObj.getStore().addListener('load', function (store) {
                            var combobox = Ext.ComponentQuery.query('combobox[name="tableCombobox1"]')[0];
                            var length = store.getData().length;
                            if (length > 0) {
                                var defaultValue = store.getData().items[0].id;
                                if (!!defaultValue) {
                                    combobox.setValue(defaultValue);
                                }
                            }
                        });
                        comboboxObj.getStore().load();
                    }
                }
            }
        ]
    });
    return tab_panel;//返回页签
}

// 截取括号中的元素
function kuohao(str) {
    var result = []; // 结果集
    while (str.indexOf("(") != -1) { // 如果包含 ( 左括号符号, 执行循环
        var rt = /(.+)?(?:\(|（)(.+)(?=\)|）)/.exec(str);
        str = rt[1]; // 剩余内容赋值给str
        result.push(rt[2]); // 最后一个括号中拆分出来的内容存入数组
    }
    return result;
}

//获取字符串中指定字符串的个数
function getStrCount(scrstr, armstr) { //scrstr 源字符串 armstr 特殊字符
    var count = 0;
    while (scrstr.indexOf(armstr) != -1) {
        scrstr = scrstr.replace(armstr, "");
        count++;
    }
    return count;
}

//初始化表格树的画板
function initColumnTreeGridPanel() {
    return Ext.create('Ext.panel.Panel', {
        region: 'center', //在左侧
        layout: 'fit', //一个子元素将充满整个容器（如果多个子元素则只有一个元素充满整个容器）
        itemId: 'columnGridLeft',
        name: 'columnGridLeft',
        flex: 5,
        border: true,
        lines: false,
        bodyStyle: 'border-width:0 5 0 0;',// 设置panel边框有无，去掉上方边框,给右侧加边框
        items: [
            //初始化左侧树结构
            initColumnTreeGrid()
        ]
    });

}

//创建数据列的表格树
function initColumnTreeGrid() {
    var treeStore = Ext.create('Ext.data.TreeStore', { //TreeStore必须用在tree.Panel中,作为数据来源
        storeId: 'treeTableByNames',
        model: 'treeModel',
        fields: ['id', 'text'],
        proxy: {
            type: "ajax",
            method: "POST",
            url: "/sys-report/getColumnNameByTableNames", //获取所有表及其字段
            reader: {
                type: "json"
            }
        },
        autoLoad: true,
        listeners: {
            // load:function (self) {
            // }
        }
    });
    field_treeGridStore = treeStore;
    var $tree = Ext.create('Ext.tree.Panel', {
        itemId: 'newTreeGridPanel',
        width: '100%',
        height: 600,
        store: treeStore,
        useArrows: true,
        rootVisible: false, //是否显示根结点
        multiSelect: true,    // 多选
        //singleExpand: true,   //单展开
        autoScroll: true,    // 自动滚屏
        columnLines: true,
        rowLines: true,
        columns: [
            {          // 列项
                xtype: 'treecolumn',
                text: '数据字段',
                width: '40%',
                sortable: true,
                menuDisabled: true,
                dataIndex: 'code'
            },
            {
                text: '计算(下拉选择)',
                width: '20%',
                dataIndex: 'doit',
                menuDisabled: true,
                align: 'center',
                sortable: true,
                editor: {
                    xtype: 'combobox',
                    allowBlank: true,
                    editable: false,
                    displayField: 'name',
                    valueField: 'code',
                    store: DebtEleStore(jisuan)
                },
                renderer: function (value, cell) {
                    //渲染数据之前进行判断，然后显示字段
                    if (value == 'COUNT') {
                        value = 'COUNT';
                    } else if (value == 'SUM') {
                        value = 'SUM';
                    } else if (value == ' ') {
                        value = ' ';
                    }
                    return value;
                }
            }, {          // 列项
                text: '注释',
                width: '40%',
                sortable: true,
                menuDisabled: true,
                dataIndex: 'text'
            }
        ],
        plugins: [ //在表格行中编辑 添加的插件
            {
                ptype: 'cellediting',
                clicksToEdit: 1,
                pluginId: 'contentGrid_treeGrid',
                clicksToMoveEditor: 1,
                listeners: {
                    beforeedit: function (editor, context) {
                        return true; //是否可编辑
                    }
                }
            }
        ],
        listeners: {
            afterlayout: function (self) {
                if (Ext.StoreMgr.get('treeTableByNames').getData().length > 0) {
                    for (var i in arrayField) {
                        //arrayField[i]= arrayField[i].replace("\t","").replace("/(^\\s*)|(\\s*$)/g","");
                        var node = self.getStore().getNodeById(arrayField[i]);
                        if (node != null) {
                            node.set('checked', true);
                        }
                    }
                    for (var i in arrayJuhe) {
                        var node = self.getStore().getNodeById(arrayJuhe[i].id);
                        if (arrayJuhe[i].doit == "SUM" && node != null) {
                            node.set('doit', 'SUM');
                            node.set('checked', true);
                        } else {
                            node.set('doit', 'COUNT');
                            node.set('checked', true);
                        }
                    }
                    arrayField = [];
                    arrayJuhe = [];

                }
            }
        }

    });
    return $tree;

}

//创建条件页签
function createGridForWhere() {
    return Ext.create('Ext.panel.Panel', {
        region: 'center', //在中部
        layout: 'fit', //一个子元素将充满整个容器（如果多个子元素则只有一个元素充满整个容器）
        itemId: 'wherePanel',
        name: 'wherePanel',
        flex: 5,
        border: true,
        lines: false,
        bodyStyle: 'border-width:10 5 10 5;',// 设置panel边框有无，去掉上方边框
        items: [
            {
                xtype: 'form',
                width: '100%',
                height: '100%',
                layout: 'column',
                autoScroll: true,
                defaults: {
                    margin: '10 5 5 5',
                    columnWidth: .99,
                    labelAlign: "right",
                    labelWidth: 100
                    // 控件默认标签宽度
                },
                items: [
                    {
                        fieldLabel: '<span  style="font-family: bold; text-align: left">已选表名</span>',
                        xtype: 'textareafield',
                        height: '5%',
                        name: 'TableSelected1',
                        allowBlank: false,
                        value: ""
                    },
                    {
                        xtype: 'textareafield',
                        // fieldLabel: '<span class="required">✶</span>',
                        height: '70%',
                        name: 'EDIT_SQL1',
                        allowBlank: false,
                        value: ""
                    }]
            }
        ]
    });
}

//创建关联页签
function createGridForJoin() {
    return Ext.create('Ext.panel.Panel', {
        region: 'center', //在中部
        layout: 'fit', //一个子元素将充满整个容器（如果多个子元素则只有一个元素充满整个容器）
        itemId: 'joinPanel',
        name: 'joinPanel',
        flex: 5,
        border: true,
        lines: false,
        bodyStyle: 'border-width:10 5 10 5;',// 设置panel边框有无，去掉上方边框
        items: [
            {
                xtype: 'form',
                width: '100%',
                height: '100%',
                layout: 'column',
                autoScroll: true,
                defaults: {
                    margin: '10 5 5 5',
                    columnWidth: .99,
                    labelAlign: "right",
                    labelWidth: 100
                    // 控件默认标签宽度
                },
                items: [
                    {
                        fieldLabel: '<span  style="font-family: bold; text-align: left">已选表名</span>',
                        xtype: 'textareafield',
                        height: '5%',
                        name: 'TableSelected',
                        allowBlank: false,
                        value: ""
                    },
                    {
                        xtype: 'textareafield',
                        // fieldLabel: '<span class="required">✶</span>',
                        height: '70%',
                        name: 'EDIT_SQL',
                        allowBlank: false,
                        value: ""
                    }]
            }
        ]
    });
}

//初始化数据表页签的左侧的树结构
function initTableTreeLeft() {
    return Ext.create('Ext.panel.Panel', {
        region: 'west', //在左侧
        layout: 'fit', //一个子元素将充满整个容器（如果多个子元素则只有一个元素充满整个容器）
        itemId: 'sqlGridLeft',
        name: 'sqlGridLeft',
        flex: 5,
        border: true,
        lines: false,
        bodyStyle: 'border-width:0 5 0 0;',// 设置panel边框有无，去掉上方边框
        items: [initTableTreeLeftContent()] //创建一个树结构 //用来显示树状的表
    });
}

//初始化数据表页签的右侧表格结构
//初始化右侧panel
function initTableGridRight() {
    return Ext.create('Ext.panel.Panel', {
        region: 'center',
        layout: 'fit',
        height: '100%',
        itemId: 'sqlGridRight',
        name: 'sqlGridRight',
        flex: 4,
        border: true,
        lines: true,
        bodyStyle: 'border-width:0 0 0 0;',// 设置panel边框有无，去掉上方边框
        items: [initTableGridRight_panel()]
    });
}

//创建数据表下左侧树内容
function initTableTreeLeftContent() {
    //创建一个搜索框
    var tbarsearch = [//搜索区域
        {
            xtype: 'textfield', //文本字段 A basic text field
            width: '80%', //宽度
            name: 'search_text',
            emptyText: '请输入数据表名称检索',
            enableKeyEvents: true, //回车触发
            listeners: { //监听器 用来遍历整棵树，然后找到对应的结点
                keypress: function (self, e) {
                    if (e.getKey() == Ext.EventObject.ENTER) {
                        // gridSearch();
                        treeSearch(self.up('treepanel'));
                    }
                }
            }
        },
        {
            xtype: 'button',
            text: '搜索',
            handler: function (self) {
                treeSearch(self.up('treepanel'));
            }
        }
    ];

    //左右箭头
    var tbar = [{
        xtype: 'button', //代表按钮
        text: '<center><span class="glyphicon glyphicon-arrow-right"></span></center>',
        width: 45, //宽度 不加单引号是像素单位，加单引号之后就是字符串，需要加单位
        name: 'right',
        handler: function (btn) {
            var tree = Ext.ComponentQuery.query('treepanel#tableTreeGridPanel')[0]; //获取树的列表
            var jobSelectStore = tree.getView().getChecked(); //获取选中的对象
            var jobGrid = DSYGrid.getGrid('tableOrderGrid'); //获取右侧表格对象
            jobGrid.getStore().removeAll(); //清空右侧表格数据
            jobGrid.getStore().insert(0, jobSelectStore);//将左侧选中的对象添加到右侧
        }
    }, {
        xtype: 'button',
        text: '<center><span class="glyphicon glyphicon-arrow-left"></span></center>',
        width: '45px',
        name: 'left',
        handler: function (btn) {
            var grid = DSYGrid.getGrid('tableOrderGrid'); //获取右侧表格对象
            var store = grid.getStore(); //获取数据
            var record = grid.getSelectionModel().getSelection()[0];//获取右侧表格选中的记录
            if (record != undefined) {
                //获取左侧树的对象
                var tree = Ext.ComponentQuery.query('treepanel#tableTreeGridPanel')[0];
                //通过树的id获取树的节点
                var node = tree.getStore().getNodeById(record.data.id);
                if (node != null) {
                    //将节点的选中状态置为false
                    node.set('checked', false);
                }
                //移除选中的记录
                store.remove(record);
            }
        }
    }];
    //获取初始化左侧树的表数据 所有的数据都是一个Store 查到的数据存放到Store中
    var store = Ext.create('Ext.data.TreeStore', { //TreeStore必须用在tree.Panel中,作为数据来源
        storeId: 'tableTranStore',
        model: 'treeModel',
        fields: ['id', 'text'],
        proxy: {
            type: "ajax",
            method: "POST",
            url: "/sys-report/getResourceAllTable", //获取所有表信息
            reader: {
                type: "json"
            }
        },
        autoLoad: true
    });
    //创建一个树，用来显示所有表的信息
    var tree = new Ext.tree.Panel({
        itemId: 'tableTreeGridPanel',
        store: store, //数据源的获取
        tbar: tbarsearch,//配置左侧顶部查询按钮工具
        border: true,
        checkbox: true, //多选框
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'right',
            border: 0,
            style: 'margin-top: 35%',
            items: tbar
        }],//要作为停靠项添加到此面板的一个或一系列组件。停靠的项目可以停靠在面板的顶部、右侧、左侧或底部。这通常用于工具栏或标签栏:
        rootVisible: false, //隐藏根节点
        columns: [

            {
                xtype: 'treecolumn',
                header: '可选表名',  //设置表头信息
                dataIndex: 'text',  //显示的数据(通过哪个字段来显示)
                align: 'left', //加载的树的对齐方式
                width: '98%'
            }
        ],
        selModel: {
            mode: "MULTI"     //s是否多选，默认多选,"SINGLE"/"SIMPLE"/"MULTI"
        },
        listeners: {
            afterlayout: function (self) {
                var data = arrayTableName;
                for (var i in data) {
                    var node = self.getStore().getNodeById(data[i]);
                    if (node != null) {
                        node.set('checked', true);
                        if (i == 0) {
                            Ext.ComponentQuery.query('#tableTreeGridPanel')[0].getView().scrollTo(0, Ext.ComponentQuery.query('#tableTreeGridPanel')[0].getView().getNodes()[0].clientHeight * (node.raw.index), true);
                        }
                    }
                }
                arrayTableName = [];
            }
        }
    });
    return tree;
}

//创建右侧panel下的表格
function initTableGridRight_panel() {
    //定义一个表格
    var fieldHeadJson = [{
        dataIndex: "text",
        type: "string",
        text: "选中表名"
    }, {
        dataIndex: "id",
        type: "string",
        text: "选中表名id",
        hidden: true
    }]; //表格中显示的字段 以及字段的属性 类型
    var config = {
        //表格的配置
        headerConfig: {
            headerJson: fieldHeadJson,
            columnAutoWidth: true //列宽自动配置
        },
        autoLoad: false, //自动加载
        border: true,
        itemId: 'tableOrderGrid',
        hideHeaders: false, //是否隐藏表头
        pageConfig: {
            enablePage: false
        },
        data: [],
        scrollable: true //滚动条
    };
    var grid = DSYGrid.createGrid(config); //创建表格
    return grid; //返回一个表格
}

//获取数据表页签选中的表
function getDataFromTable() {
    //获取数据表页加载到右侧的表名
    var grid = DSYGrid.getGrid('tableOrderGrid');//获取数据表页签下右侧表格的对象
    var store = grid.getStore(); //获取数据
    var data_table = []; //定义一个空数组，用来存放遍历的表格的数据
    store.each(function (record, index, count) {
        //将表格中的数据添加到数组中，构造json串
        data_table.push({
            id: record.getData().id,
            code: record.getData().code,
            name: record.getData().text
        });
    });
    return data_table;
}

///////////////////////////////////////////////////////////
//初始化排序页签左侧
function initOrderByTreeLeft() {
    return Ext.create('Ext.panel.Panel', {
        region: 'west', //在左侧
        layout: 'fit', //一个子元素将充满整个容器（如果多个子元素则只有一个元素充满整个容器）
        itemId: 'columnGridLeft',
        name: 'columnGridLeft',
        flex: 4,
        border: true,
        lines: false,
        bodyStyle: 'border-width:0 5 0 0;',// 设置panel边框有无，去掉上方边框,给右侧加边框
        items: [
            //初始化左侧树结构
            initOrderByTreeGrid()
        ]
    });

}
var comboxSwitchOrderBy = [] ;//临时切换选中表选中字段存储数组
//初始化排序列页签树
function initOrderByTreeGrid() {
    //创建按钮对象
    //左右箭头
    var tbar = [{
        xtype: 'button', //代表按钮
        text: '<center><span class="glyphicon glyphicon-arrow-right"></span></center>',
        width: 45, //宽度 不加单引号是像素单位，加单引号之后就是字符串，需要加单位
        name: 'right',
        handler: function (btn) {
            var tree = Ext.ComponentQuery.query('treepanel#columnOrderByGridPanel')[0]; //获取树的列表
            // var jobSelectStore = tree.getView().getChecked()[0].data; //获取选中的对象
            var jobSelectStore = tree.getView().getChecked(); //获取选中的对象
            var jobGrid = DSYGrid.getGrid('sortOrderGrid'); //获取右侧表格对象
            //给表格新添加属性并且赋值
            //获取选中表的值
            // jobSelectStore["tableNameSelected"] = Ext.ComponentQuery.query("#tablename")[0].getValue();
            //设置排序
            for (var i = 0; i < jobSelectStore.length; i++) {

                jobSelectStore[i].data["SORT"] = "ASC";
                jobGrid.getStore().insert(i, jobSelectStore);//将左侧选中的对象添加到右侧
                if (!comboxSwitchOrderBy.includes(jobSelectStore[i].data.id)){
                    comboxSwitchOrderBy.push(jobSelectStore[i].data.id);
                }

            }
            // Ext.ComponentQuery.query('treepanel#columnOrderByGridPanel')[0].getStore().getNodeById(Ext.ComponentQuery.query('treepanel#columnOrderByGridPanel')[0].getView().getChecked()[0].data.id).set('checked', false);

        }
    }, {
        xtype: 'button',
        text: '<center><span class="glyphicon glyphicon-arrow-left"></span></center>',
        width: '45px',
        name: 'left',
        handler: function (btn) {
            var grid = DSYGrid.getGrid("sortOrderGrid");
            var store = grid.getStore();
            var record = grid.getSelectionModel().getSelection()[0];
            if (record != undefined) {
                var tree = Ext.ComponentQuery.query('treepanel#columnOrderByGridPanel')[0];
                var node = tree.getStore().getNodeById(record.data.id);
                if (node != null) {
                    node.set('checked', false);
                }
                store.remove(record);
                comboxSwitchOrderBy.splice(comboxSwitchOrderBy.indexOf(record.data.id.toString()),1)
                arrayOrder.splice(arrayOrder.indexOf(record.data.id.toString()),1)
            }
        }
    }];
    //根据表名请求列名
    var storeColumn = Ext.create('Ext.data.TreeStore', {
        storeId: 'orderByTranStore',
        model: 'treeModel',
        fields: ['id', 'text'],
        proxy: {
            extraParams: {},
            type: "ajax",
            method: "POST",
            url: "/sys-report/getColumnNameByTableName", //获取表对应列信息
            reader: {
                type: "json"
            }
        },
        autoLoad: true
    });


    //创建一个树 -用来通过表格查询列名进行显示，用来显示对应表的字段的信息

    var tree = new Ext.tree.Panel({
        itemId: 'columnOrderByGridPanel', //数据列的名称
        store: storeColumn, //用来显示根据表名查询到的对应的字段
        border: true,
        // checkbox: true, //多选框
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'right',
            border: 0,
            style: 'margin-top: 35%',
            items: tbar //左右箭头按钮的布局
        }],
        rootVisible: false,
        columns: [
            //设置表头信息
            {
                xtype: 'treecolumn',
                header: '可选列名',
                dataIndex: 'text',
                align: 'left',
                width: '100%'
            }
        ],
        //下拉框的工具按钮
        tbar: [
            {
                fieldLabel: '请选择表名',
                name: 'tableCombobox1',
                itemId: "tablename",
                xtype: 'combobox',
                displayField: 'name',//对应的下拉框实际值
                valueField: 'code', //对应的下拉框显示值
                editable: false,
                emptyText: "--请选择--",
                width: "80%",
                labelAlign: 'right',
                listeners: {
                    //选中下拉框执行的方法
                    change: function (newValue, oldValue, eOpts) {
                        var comboboxData = newValue.value; //选中的下拉框的数据
                        //发起请求，根据表名查询字段名称
                        storeColumn.getProxy().extraParams = {
                            selectedTableName: comboboxData
                        };  //设置请求参数
                        storeColumn.reload();
                    }
                }
            }

        ],
        selModel: {
            mode: "MULTI"     //s是否多选，默认多选,"SINGLE"/"SIMPLE"/"MULTI"
        },
        listeners: {
            afterlayout: function (self) {
                if (Ext.StoreMgr.get('orderByTranStore').getData().length > 1) {

                    for (var i in arrayOrder) {
                        var node = self.getStore().getNodeById(arrayOrder[i]);
                        if (node != null) {
                            node.set('checked', true);
                        }
                    }
                    // arrayOrder = [];
                }
                //临时切换表名勾选之前选中的列名
                for (var i in comboxSwitchOrderBy) {
                    var ss = Ext.ComponentQuery.query('treepanel#columnOrderByGridPanel')[0].getView();
                    var node = ss.getStore().getNodeById(comboxSwitchOrderBy[i]);
                    if (node != null) {
                        node.set('checked', true);
                    }
                }
            }
        }
    });
    return tree;
}

//初始化排序页签右侧表格
function initOrderByGridRigth() {
    return Ext.create('Ext.panel.Panel', {
        region: 'center',
        layout: 'fit',
        height: '100%',
        itemId: 'orderbyGridRight',
        name: 'orderbyGridRight',
        flex: 5,
        border: true,
        lines: true,
        bodyStyle: 'border-width:0 0 0 0;',// 设置panel边框有无，去掉上方边框
        items: [initOrderByGridRigth_panel()]
    });
}

//创建排序页签右侧panel下的表格
function initOrderByGridRigth_panel() {
    //定义上移下移按钮
    var movebar = [
        {
            xtype: 'button',
            text: '上移',
            name: 'up',
            handler: function (btn) {
                var grid = DSYGrid.getGrid('sortOrderGrid');
                var store = grid.getStore();
                var record = grid.getSelectionModel().getSelection()[0];
                var index = store.indexOf(record);
                if (index > 0) {
                    store.removeAt(index);
                    store.insertData(index - 1, record);
                    grid.getSelectionModel().selectRange(index - 1, index - 1);
                    grid.getView().refresh();
                    grid.getView().addRowCls(record, "x-grid-item-click");

                }
            }
        }, {
            xtype: 'button',
            text: '下移',
            name: 'down',
            disabled: false,
            handler: function (btn) {
                var grid = DSYGrid.getGrid('sortOrderGrid');
                var store = grid.getStore();
                var record = grid.getSelectionModel().getSelection()[0];
                var index = store.indexOf(record);
                if (index < store.getCount() - 1) {
                    store.removeAt(index);
                    store.insertData(index + 1, record);
                    grid.getSelectionModel().selectRange(index + 1, index + 1);
                    grid.getView().refresh();//刷新行号
                    grid.getView().addRowCls(record, "x-grid-item-click");
                }
            }
        }
    ];
    var sort = [
        {id: "0", code: "ASC", name: "升序"},
        {id: "1", code: "DESC", name: "降序"}
    ]


    //定义一个表格
    var fieldHeadJson = [
        {
            dataIndex: "parentId",
            type: "string",
            text: "选中表名",
            width: 200,
        },
        {
            dataIndex: "code",
            type: "string",
            text: "选中列名",
            width: 100,
        },
        {
            dataIndex: "id",
            type: "string",
            text: "选中列名id",
            width: 100,
            hidden: true
        },
        {
            dataIndex: "SORT",
            type: "string",
            text: "排序方式(可编辑)",
            width: 100,
            editor: {
                xtype: 'combobox',
                allowBlank: true,
                editable: false,
                displayField: 'name',
                valueField: 'code',
                store: DebtEleStore(sort)
            },
            renderer: function (value, cell) {
                //渲染数据之前进行判断，然后显示字段
                if (value == 'ASC') {
                    value = '升序';
                } else if (value == 'DESC') {
                    value = '降序';
                }
                return value;
            }

        }

    ]; //表格中显示的字段 以及字段的属性 类型
    var config = {
        //表格的配置
        headerConfig: {
            headerJson: fieldHeadJson,
            columnAutoWidth: true //列宽自动配置
        },
        autoLoad: false, //自动加载
        border: true,
        itemId: 'sortOrderGrid',
        hideHeaders: false, //是否隐藏表头
        pageConfig: {
            enablePage: false
        },
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'right',
            items: movebar, //上移下移工具栏
            hidden: false
        }],
        data: [],
        scrollable: true, //滚动条
        plugins: [ //在表格行中编辑 添加的插件
            {
                ptype: 'cellediting',
                clicksToEdit: 1,
                pluginId: 'contentGrid_cellediting',
                clicksToMoveEditor: 1,
                listeners: {
                    beforeedit: function (editor, context) {
                        return true;//是否可编辑
                    }
                }
            }
        ]
    };
    var grid = DSYGrid.createGrid(config); //创建表格
    return grid; //返回一个表格
}

///////////////////////////////
//初始化分组页签组件  ---------新添加的
//初始化分组页签左侧
function initGroupByTreeLeft() {
    return Ext.create('Ext.panel.Panel', {
        region: 'west', //在左侧
        layout: 'fit', //一个子元素将充满整个容器（如果多个子元素则只有一个元素充满整个容器）
        itemId: 'groupGridLeft',
        name: 'groupGridLeft',
        flex: 4,
        border: true,
        lines: false,
        bodyStyle: 'border-width:0 5 0 0;',// 设置panel边框有无，去掉上方边框,给右侧加边框
        items: [
            //初始化左侧树结构
            initGroupByTreeGrid()
        ]
    });

}
var comboxSwitchGroupBy= []; //定义分组页签中更换表名选中字段临时存储数组

//初始化分组列页签树
function initGroupByTreeGrid() {
    //创建按钮对象
    //左右箭头
    var tbar = [{
        xtype: 'button', //代表按钮
        text: '<center><span class="glyphicon glyphicon-arrow-right"></span></center>',
        width: 45, //宽度 不加单引号是像素单位，加单引号之后就是字符串，需要加单位
        name: 'right',
        handler: function (btn) {
            var tree = Ext.ComponentQuery.query('treepanel#columnGroupByGridPanel')[0]; //获取树的列表
            // var jobSelectStore = tree.getView().getChecked()[0].data; //获取选中的对象
            var jobSelectStore = tree.getView().getChecked(); //获取选中的对象
            var jobGrid = DSYGrid.getGrid('groupGrid'); //获取右侧表格对象
            //给表格新添加属性并且赋值
            for (var i = 0; i < jobSelectStore.length; i++) {
                jobGrid.getStore().insert(i, jobSelectStore);//将左侧选中的对象添加到右侧
                if (!comboxSwitchGroupBy.includes(jobSelectStore[i].data.id)){
                    //将勾选过的字段添加到临时数组中，用来切换表名时使用
                    comboxSwitchGroupBy.push(jobSelectStore[i].data.id);
                }

            }
        }
    }, {
        xtype: 'button',
        text: '<center><span class="glyphicon glyphicon-arrow-left"></span></center>',
        width: '45px',
        name: 'left',
        handler: function (btn) {
            var grid = DSYGrid.getGrid("groupGrid");
            var store = grid.getStore();
            var record = grid.getSelectionModel().getSelection()[0];
            if (record != undefined) {
                var tree = Ext.ComponentQuery.query('treepanel#columnGroupByGridPanel')[0];
                var node = tree.getStore().getNodeById(record.data.id);
                if (node != null) {
                    node.set('checked', false);
                }
                store.remove(record);
                // comboxSwitch.pop(record.data.id.toString());
                comboxSwitchGroupBy.splice(comboxSwitchGroupBy.indexOf(record.data.id.toString()),1)
                // arrayGroup.pop(record.data.id.toString())
                arrayGroup.splice(arrayGroup.indexOf(record.data.id.toString()),1)
            }
        }
    }];
    //根据表名请求列名
    var storeColumn = Ext.create('Ext.data.TreeStore', {
        storeId: 'groupByTranStore',
        model: 'treeModel',
        fields: ['id', 'text'],
        proxy: {
            extraParams: {},
            type: "ajax",
            method: "POST",
            url: "/sys-report/getColumnNameByTableName", //获取表对应列信息
            reader: {
                type: "json"
            }
        },
        autoLoad: true
    });


    //创建一个树 -用来通过表格查询列名进行显示，用来显示对应表的字段的信息

    var tree = new Ext.tree.Panel({
        itemId: 'columnGroupByGridPanel', //数据列的名称
        store: storeColumn, //用来显示根据表名查询到的对应的字段
        border: true,
        // checkbox: true, //多选框
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'right',
            border: 0,
            style: 'margin-top: 35%',
            items: tbar //左右箭头按钮的布局
        }],
        rootVisible: false,
        columns: [
            //设置表头信息
            {
                xtype: 'treecolumn',
                header: '可选列名',
                dataIndex: 'text',
                align: 'left',
                width: '100%'
            }
        ],
        //下拉框的工具按钮
        tbar: [
            {
                fieldLabel: '请选择表名',
                name: 'tableCombobox2',
                itemId: "tablename1",
                xtype: 'combobox',
                displayField: 'name',//对应的下拉框实际值
                valueField: 'code', //对应的下拉框显示值
                editable: false,
                emptyText: "--请选择--",
                width: "80%",
                labelAlign: 'right',
                listeners: {
                    //选中下拉框执行的方法
                    change: function (newValue, oldValue, eOpts) {
                        var comboboxData = newValue.value; //选中的下拉框的数据
                        //发起请求，根据表名查询字段名称
                        storeColumn.getProxy().extraParams = {
                            selectedTableName: comboboxData
                        };  //设置请求参数
                        storeColumn.load();
                    }

                }
            }

        ],
        selModel: {
            mode: "MULTI"     //s是否多选，默认多选,"SINGLE"/"SIMPLE"/"MULTI"
        },
        listeners: {
            afterlayout: function (self) {
                    if (Ext.StoreMgr.get('groupByTranStore').getData().length > 1) {
                        for (var i in arrayGroup) {
                            var node = self.getStore().getNodeById(arrayGroup[i]);
                            if (node != null) {
                                node.set('checked', true);
                            }
                        }
                        // arrayGroup = [];
                    }
                    //临时切换表名勾选之前选中的列名
                    for (var i in comboxSwitchGroupBy) {
                        var ss = Ext.ComponentQuery.query('treepanel#columnGroupByGridPanel')[0].getView();
                        var node = ss.getStore().getNodeById(comboxSwitchGroupBy[i]);
                        if (node != null) {
                            node.set('checked', true);
                        }
                    }
            }
        }
    });
    return tree;
}

//初始化分组页签右侧表格
function initGroupByGridRigth() {
    return Ext.create('Ext.panel.Panel', {
        region: 'center',
        layout: 'fit',
        height: '100%',
        itemId: 'groupGridRight',
        name: 'groupGridRight',
        flex: 5,
        border: true,
        lines: true,
        bodyStyle: 'border-width:0 0 0 0;',// 设置panel边框有无，去掉上方边框
        items: [initGroupByGridRigth_panel()]
    });
}

//创建排序页签右侧panel下的表格
function initGroupByGridRigth_panel() {
    //定义上移下移按钮
    var movebar = [
        {
            xtype: 'button',
            text: '上移',
            name: 'up',
            handler: function (btn) {
                var grid = DSYGrid.getGrid('groupGrid');
                var store = grid.getStore();
                var record = grid.getSelectionModel().getSelection()[0];
                var index = store.indexOf(record);
                if (index > 0) {
                    store.removeAt(index);
                    store.insertData(index - 1, record);
                    grid.getSelectionModel().selectRange(index - 1, index - 1);
                    grid.getView().refresh();
                    grid.getView().addRowCls(record, "x-grid-item-click");

                }
            }
        }, {
            xtype: 'button',
            text: '下移',
            name: 'down',
            disabled: false,
            handler: function (btn) {
                var grid = DSYGrid.getGrid('groupGrid');
                var store = grid.getStore();
                var record = grid.getSelectionModel().getSelection()[0];
                var index = store.indexOf(record);
                if (index < store.getCount() - 1) {
                    store.removeAt(index);
                    store.insertData(index + 1, record);
                    grid.getSelectionModel().selectRange(index + 1, index + 1);
                    grid.getView().refresh();//刷新行号
                    grid.getView().addRowCls(record, "x-grid-item-click");
                }
            }
        }
    ];
    //定义一个表格
    var fieldHeadJson = [
        {
            dataIndex: "parentId",
            type: "string",
            text: "选中表名",
            width: 200
        },
        {
            dataIndex: "code",
            type: "string",
            text: "选中列名",
            width: 100
        },
        {
            dataIndex: "id",
            type: "string",
            text: "选中列名id",
            width: 100,
            hidden: true
        }

    ]; //表格中显示的字段 以及字段的属性 类型
    var config = {
        //表格的配置
        headerConfig: {
            headerJson: fieldHeadJson,
            columnAutoWidth: true //列宽自动配置
        },
        autoLoad: false, //自动加载
        stripeRows: true,
        border: true,
        itemId: 'groupGrid',
        hideHeaders: false, //是否隐藏表头
        pageConfig: {
            enablePage: false
        },
        dockedItems: [{
            xtype: 'toolbar',
            dock: 'right',
            items: movebar, //上移下移工具栏
            hidden: false
        }],
        data: [],
        scrollable: true //滚动条
    };
    var grid = DSYGrid.createGrid(config); //创建表格
    return grid; //返回一个表格
}

//sql拼接函数
function jointSQL() {
    var sql1 = "SELECT ";
    var sql2 = "FROM  ";
    var sql3 = "WHERE  ";
    var sql4 = "GROUP BY  "; //分组
    var sql5 = "ORDER BY  "; //排序
    // 获取字段页签的数据
    var checked = Ext.ComponentQuery.query('treepanel#newTreeGridPanel')[0].getChecked();
    if (checked.length === 0 && arrayField.length === 0) {
        sql1 = sql1 + "   * ";
        sql1 = sql1 + "\n";
    } else {
        //遍历选中的字段
        for (var i = 0; i < checked.length; i++) {
            //判断当前行是否进行了聚合函数
            var aggregation = checked[i].data.doit;
            if (!!aggregation) {
                sql1 += "\n" + "    " + aggregation + "(" + checked[i].data.id + ")";
            } else {
                sql1 += "\n" + "    " + checked[i].data.id;
            }
            if (i !== checked.length - 1) {
                sql1 += ","
            }
        }
        // 防止回显时字段未回显到界面上就点击了确定导致字段丢失
        for (var i = 0; i < arrayField.length; i++) {
            if (i === 0) {
                sql1 += "\n";
            }
            sql1 += "    " + arrayField[i];
            if (i !== arrayField.length - 1) {
                sql1 += ",\n";
            }
        }
    }
    //获取关联页签的数据
    var getJoin = Ext.ComponentQuery.query('textareafield[name="EDIT_SQL"]')[1].getValue();
    tableAlias = [];
    var tables = getDataFromTable();
    if (getJoin != "") {
        //将输入框的转化为大写
        sql2 = "  \n" + getJoin.toUpperCase();
        // 解析表别名
        var keywords = ['FROM', 'LEFT', 'RIGHT', 'INNER', 'ON', ','];
        var joinSplits = getJoin.split(/\s+/);
        $.each(joinSplits, function (index, word) {
            $(tables).each(function () {
                if (word === this.code) {
                    if (!!joinSplits[index + 1] && keywords.indexOf(joinSplits[index + 1]) === -1) {
                        tableAlias.push({tableName: this.code, tableAlias: joinSplits[index + 1]});
                    }
                    return false;
                }
            });
        });
    } else {
        sql2 = "  \n" + sql2 + tables[0].code+" T";
        tableAlias.push({tableName: tables[0].code, tableAlias: "T"});

    }
    //获取条件页签的数据
    var getWhere = Ext.ComponentQuery.query('textareafield[name="EDIT_SQL1"]')[0].getValue();
    if (getWhere != "") {
        sql3 = "\n" + sql3 + getWhere.toLocaleUpperCase();
    } else {
        sql3 = "";
    }
    //获取分组页签的数据
    var groupStore = Ext.ComponentQuery.query('#groupGrid')[0].getStore();
    var groupData = groupStore.data.items;
    if (groupData.length != 0) {
        for (var i = 0; i < groupData.length; i++) {
            //var aggregation = checked[i].data.doit;
            if (i == groupData.length - 1) {
                sql4 = "\n" + sql4 + " ";
                sql4 = sql4 + groupData[i].data.parentId + "." + groupData[i].data.code;
                break;
            }
            sql4 = "\n" + sql4 + " ";
            sql4 = sql4 + groupData[i].data.parentId + "." + groupData[i].data.code + " ,";
        }
    } else {
        if (aggregation != undefined) {
            Ext.MessageBox.alert("提示框", "需要选择分组");
        }
        sql4 = "";
    }
    //获取排序页签的数据
    var orderStore = Ext.ComponentQuery.query('#sortOrderGrid')[0].getStore();
    var orderData = orderStore.data.items;
    if (orderData.length != 0) {
        for (var i = 0; i < orderData.length; i++) {
            //var aggregation = checked[i].data.doit;
            if (i == orderData.length - 1) {
                sql5 = "\n" + sql5 + " ";
                sql5 = sql5 + orderData[i].data.parentId + "." + orderData[i].data.code + " " + orderData[i].data.SORT;
                break;
            }
            sql5 = "\n" + sql5 + " ";
            sql5 = sql5 + orderData[i].data.parentId + "." + orderData[i].data.code + " " + orderData[i].data.SORT + ",";
        }
    } else {
        sql5 = "";
    }
    //构造sql
    var finalSql = sql1 + sql2 + sql3 + sql4 + sql5;
    finalSql = finalSql.replaceAll("\n+", "\n");
    if (!!tableAlias) {
        $(tableAlias).each(function () {
            finalSql = finalSql.replaceAll(this.tableName + '\\.', this.tableAlias + ".");
        });
    }
    Ext.ComponentQuery.query('textareafield[name="EDIT_SQL"]')[0].setValue(finalSql);
    //重置请求参数
}
